﻿using Microsoft.AspNetCore.Mvc;
using WMS.Service.Minio;

[ApiController]
[Route("api/[controller]")]
public class FilesController : ControllerBase
{
    private readonly IMinioService _minioService;

    public FilesController(IMinioService minioService)
    {
        _minioService = minioService;
    }

    /// <summary>
    /// 上传文件
    /// </summary>
    [HttpPost("upload")]
    public async Task<IActionResult> UploadFile(IFormFile file, [FromQuery] string bucketName = null)
    {
        if (file == null || file.Length == 0)
            return BadRequest(new { success = false, message = "文件不能为空" });

        try
        {
            var objectName = await _minioService.UploadFileAsync(file, bucketName);
            return Ok(new
            {
                success = true,
                objectName = objectName,
                originalFileName = file.FileName,
                fileSize = file.Length,
                message = "文件上传成功"
            });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new
            {
                success = false,
                message = $"文件上传失败: {ex.Message}"
            });
        }
    }

    /// <summary>
    /// 下载文件
    /// </summary>
    [HttpGet("download/{objectName}")]
    public async Task<IActionResult> DownloadFile(string objectName, [FromQuery] string bucketName = null)
    {
        try
        {
            var stream = await _minioService.DownloadFileAsync(objectName, bucketName);

            // 获取文件扩展名
            var extension = Path.GetExtension(objectName);
            var contentType = GetContentType(extension);

            return File(stream, contentType, objectName);
        }
        catch (FileNotFoundException)
        {
            return NotFound(new { success = false, message = "文件不存在" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// 删除文件
    /// </summary>
    [HttpDelete("{objectName}")]
    public async Task<IActionResult> DeleteFile(string objectName, [FromQuery] string bucketName = null)
    {
        try
        {
            var result = await _minioService.DeleteFileAsync(objectName, bucketName);
            if (result)
            {
                return Ok(new { success = true, message = "文件删除成功" });
            }
            else
            {
                return NotFound(new { success = false, message = "文件不存在" });
            }
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// 列出所有存储桶
    /// </summary>
    [HttpGet("buckets")]
    public async Task<IActionResult> ListBuckets()
    {
        try
        {
            var buckets = await _minioService.ListBucketsAsync();
            return Ok(new { success = true, buckets });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// 检查存储桶是否存在
    /// </summary>
    [HttpGet("bucket-exists")]
    public async Task<IActionResult> BucketExists([FromQuery] string bucketName)
    {
        try
        {
            var exists = await _minioService.BucketExistsAsync(bucketName);
            return Ok(new { success = true, bucketName, exists });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = ex.Message });
        }
    }

    /// <summary>
    /// 创建存储桶
    /// </summary>
    [HttpPost("create-bucket")]
    public async Task<IActionResult> CreateBucket([FromQuery] string bucketName)
    {
        try
        {
            await _minioService.CreateBucketAsync(bucketName);
            return Ok(new { success = true, message = $"存储桶 '{bucketName}' 创建成功" });
        }
        catch (Exception ex)
        {
            return StatusCode(500, new { success = false, message = ex.Message });
        }
    }

    private string GetContentType(string extension)
    {
        return extension.ToLower() switch
        {
            ".pdf" => "application/pdf",
            ".jpg" or ".jpeg" => "image/jpeg",
            ".png" => "image/png",
            ".txt" => "text/plain",
            ".doc" => "application/msword",
            ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            ".xls" => "application/vnd.ms-excel",
            ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            _ => "application/octet-stream"
        };
    }
}